<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/9/24
 * Time: 17:56
 */
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Service\Admin\TagService;
use App\Constant\ErrorConstant;

class TagController extends BaseController
{
    protected $service;

    public function __construct(Request $request, TagService $service)
    {
        parent::__construct($request);

        $this->service  =   $service;
    }

    /**
     * 标签列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function listTag()
    {
        [$flag, $result]    =   $this->service->tagList();
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::ADMIN_TAG_LIST_ERROR, $result);
        }
    }

    /**
     * 标签删除
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteTag()
    {
        $validator  =   Validator::make($this->request->post(), [
            'tag_id'       =>  'required|integer',
        ], [
            'tag_id.required'  =>  '标签ID不能为空',
            'tag_id.integer'   =>  '标签ID必须为整数',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse(ErrorConstant::ADMIN_TAG_DELETE_ERROR, $validator->errors()->first());
        }

        $tag_id    =   (int) $this->request->post('tag_id');

        [$flag, $result]    =   $this->service->tagDelete($tag_id);
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::ADMIN_TAG_DELETE_ERROR, $result);
        }
    }

    /**
     * 标签添加
     * @return \Illuminate\Http\JsonResponse
     */
    public function addTag()
    {
        $validator  =   Validator::make($this->request->all(), [
            'tag_name'  =>  'required|string|max:30',
            'sorting'   =>  'required|integer',
            'tag_desc'  =>  'string|max:200',
        ], [
            'tag_name.required' =>  '标签名称不能为空',
            'tag_name.string'   =>  '标签名称只能为字符',
            'tag_name.max'      =>  '标签名称过长',

            'sorting.required'  =>  '标签排序不能为空',
            'sorting.integer'   =>  '标签排序必须为数字',

            'tag_desc.string'   =>  '标签描述只能为字符',
            'tag_desc.max'      =>  '标签描述过长',

        ]);

        if ($validator->fails()) {
            return $this->errorResponse(ErrorConstant::ADMIN_TAG_ADD_ERROR, $validator->errors()->first());
        }

        $params =   $this->request->post();
        [$flag, $result]    =   $this->service->tagAdd($params);
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::ADMIN_TAG_ADD_ERROR, $result);
        }
    }

}

